package com.dream.web.controller.monitor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.dream.common.constant.CacheConstants;
import com.dream.common.core.domain.AjaxResult;
import com.dream.web.system.domain.SysCache;
import jakarta.annotation.Resource;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 缓存监控
 *
 * @author hlm
 */
@RestController
@RequestMapping("/monitor/cache")
public class MonCacheController {

    private final static List<SysCache> caches = new ArrayList<>();

    static {
        caches.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息"));
        caches.add(new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息"));
        caches.add(new SysCache(CacheConstants.SYS_DICT_KEY, "数据字典"));
        caches.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
        caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
        caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
        caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
    }

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 获取缓存监控统计信息
     *
     * @return 结果
     */
    @PreAuthorize("@ss.hasPerm('monitor:cache:list')")
    @GetMapping()
    public AjaxResult getInfo() {
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::info);
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.serverCommands().info("commandStats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        if (commandStats != null) {
            commandStats.stringPropertyNames().forEach(key -> {
                Map<String, String> data = new HashMap<>(4);
                String property = commandStats.getProperty(key);
                data.put("name", StrUtil.removePrefix(key, "cmdstat_"));
                data.put("value", StrUtil.subBetween(property, "calls=", ",usec"));
                pieList.add(data);
            });
        }

        // 返回
        Map<String, Object> result = new HashMap<>(4);
        result.put("info", info);
        result.put("dbSize", dbSize);
        result.put("commandStats", pieList);
        return AjaxResult.success(result);
    }

    /**
     * 获取缓存列表
     *
     * @return 结果
     */
    @PreAuthorize("@ss.hasPerm('monitor:cache:list')")
    @GetMapping("/getNames")
    public AjaxResult cache() {
        return AjaxResult.success(caches);
    }

    /**
     * 根据缓存名称获取键名列表
     *
     * @param cacheName 缓存名称
     * @return 结果
     */
    @PreAuthorize("@ss.hasPerm('monitor:cache:list')")
    @GetMapping("/getKeys/{cacheName}")
    public AjaxResult getCacheKeys(@PathVariable String cacheName) {
        Set<String> cacheKeys = redisTemplate.keys(cacheName + "*");
        return AjaxResult.success(cacheKeys);
    }

    /**
     * 根据缓存名称、缓存键名获取缓存内容
     *
     * @param cacheName 缓存名称
     * @param cacheKey  缓存键值
     * @return 结果
     */
    @PreAuthorize("@ss.hasPerm('monitor:cache:list')")
    @GetMapping("/getValue/{cacheName}/{cacheKey}")
    public AjaxResult getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey) {
        String cacheValue = JSONUtil.toJsonStr(redisTemplate.opsForValue().get(cacheKey));
        SysCache sysCache = new SysCache(cacheName, cacheKey, cacheValue);
        return AjaxResult.success(sysCache);
    }

    /**
     * 根据缓存名称删除缓存信息
     *
     * @param cacheName 缓存名称
     * @return 结果
     */
    @PreAuthorize("@ss.hasPerm('monitor:cache:list')")
    @DeleteMapping("/clearCacheName/{cacheName}")
    public AjaxResult clearCacheName(@PathVariable String cacheName) {
        Collection<String> cacheKeys = redisTemplate.keys(cacheName + "*");
        if (cacheKeys != null) {
            redisTemplate.delete(cacheKeys);
        }
        return AjaxResult.success();
    }

    /**
     * 根据缓存键名删除缓存信息
     *
     * @param cacheKey 缓存键值
     * @return 结果
     */
    @PreAuthorize("@ss.hasPerm('monitor:cache:list')")
    @DeleteMapping("/clearCacheKey/{cacheKey}")
    public AjaxResult clearCacheKey(@PathVariable String cacheKey) {
        redisTemplate.delete(cacheKey);
        return AjaxResult.success();
    }

    /**
     * 清空缓存信息
     *
     * @return 结果
     */
    @PreAuthorize("@ss.hasPerm('monitor:cache:list')")
    @DeleteMapping("/clearCacheAll")
    public AjaxResult clearCacheAll() {
        Collection<String> cacheKeys = redisTemplate.keys("*");
        if (cacheKeys != null) {
            redisTemplate.delete(cacheKeys);
        }
        return AjaxResult.success();
    }
}
